import router, {dynamicRoutes} from '@/router'
import { getRouters } from '@/api/system/menu'
import Layout from '@/components/common/Home'


const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
    flag: 0
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      // state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      //state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      // 顶部导航菜单默认添加统计报表栏指向首页
      const index = [{
        path: 'index',
        meta: { title: '统计报表', icon: 'dashboard' }
      }]
      state.topbarRouters = routes.concat(index);
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    },
    SET_FLAG: (state, flag) => {
      state.flag = flag;
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const rdata = JSON.parse(JSON.stringify(res.data))
          console.log(rdata);
          const allRouters = getAllRoute(rdata);
          const index = getIndex(allRouters)
          let home = {};
          if (index) {
            home = {path:'/', component: Layout, redirect: index};
          } else {
            home = {path:'/', component: Layout, redirect: "/404"};
          }
          if (allRouters.length > 0) {
            home.children = allRouters;
          }
          router.addRoute(home);

          const asyncRoutes = filterDynamicRoutes(dynamicRoutes);
          router.addRoutes(asyncRoutes);

          commit('SET_SIDEBAR_ROUTERS', rdata)
          commit('SET_FLAG', 1);
          resolve()
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    let flag = false;
    if (route.component && route.path) {
      route.component = loadView(route.component);
      flag = true;
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return flag
  })
}

function getAllRoute(routerMap){
  var routes = [];
  routerMap.forEach(el => {

    if (el.component && el.path) {
      el.component = loadView(el.component);
      routes.push(el)
    }
    if (el.children && el.children.length) {
      routes = routes.concat(getAllRoute(el.children))
    }
  })
  return routes;
}

function getIndex(routes){
  let res = ''
  if (routes && routes.length > 0) {
    res = routes[0].path;
  }
  return res;
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      if (el.component === 'ParentView' && !lastRouter) {
        el.children.forEach(c => {
          c.path = el.path + '/' + c.path
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c))
            return
          }
          children.push(c)
        })
        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = []
  routes.forEach(route => {
    if (route.permissions) {
      if (auth.hasPermiOr(route.permissions)) {
        res.push(route)
      }
    } else if (route.roles) {
      if (auth.hasRoleOr(route.roles)) {
        res.push(route)
      }
    } else {
      res.push(route)
    }
  })
  return res
}

export const loadView = (view) => {
  // 使用 import 实现生产环境的路由懒加载
  return () => import(`@/components/${view}`)
}
export default permission
